import React, { useReducer, useEffect } from 'react';

const initState = {
    count: 0,
    step: 1
}
const reducer = (state, action) => {
    const { count, step } = state
    if (action.type === 'tick') {
        return { count: count + step, step }
    } else if (action.type === 'step') {
        return { count, step: action.step }
    }
}

const Reducer01 = () => {
    const [state, dispatch] = useReducer(reducer, initState)
    const { count, step } = state

    useEffect(() => {
        const t = setInterval(() => {
            dispatch({ type: 'tick' })
        }, 1000)
        return () => [
            clearInterval(t)
        ]
    }, [])
    return (
        <div>
            <h2>使用reducer</h2>
            <p>{count}</p>
            <input value={step} onChange={e => dispatch({ type: 'step', step: Number(e.target.value) })} />
        </div>
    );
}

export default Reducer01;
